/**
 * 业务表单基础的增、删、改、查
 */
import {
  init,
  list,
  del
} from "@/views/youshuda/api/BaseApi";
import {getToken} from "@/utils/auth";
import {EventMixins} from "@/views/youshuda/mixins/EventMixins"
import {DynTableMixins} from "@/views/youshuda/components/FormBuild/component/cn/youshuda/pc/table/mixin/DynTableMixins";
import {formConf} from "@/views/youshuda/components/FormBuild/generator/config";
import {hasPermissions} from '@/directive/permission/hasPermi'
import axios from "axios";

export const CrudMixins = {
  components: {
    FormItem: () => import('@/views/youshuda/components/FormItem/index'),
    Edit: () => import('@/views/youshuda/components/FormEdit/index'),
    FormBuildGuide: () => import('@/views/youshuda/base/crud/FormBuildGuide')
  },
  mixins: [EventMixins, DynTableMixins],
  computed: {
    /** 查询区按钮信息 */
    queryOperBtns() {
      let operBtns = [];
      if (this.modeConfig.crudBtnsList) {
        for (let btns of this.modeConfig.crudBtnsList) {
          if (btns.isEnabled && (btns.areaType == 'A' || btns.areaType == 'Q')) {
            operBtns.push(btns)
          }
        }
      }
      return operBtns;
    },
    /** 列表按钮区宽度 */
    listOperBtnBoxWidth() {
      let width = 200;
      if (this.table.tableBtns) {
        width = 0;
        for (let i = 0; i < this.table.tableBtns.length; i++) {
          if (i > 2) {
            break;
          }
          let btn = this.table.tableBtns[i]
          if (btn.circle) {
            width += 30;
          } else {
            width += String(btn.label).length * 20;
            if (this.isNotEmpty(btn.icon)) {
              width += 30;
            }
          }
        }
      }
      width = width<150?150:width
      return width;
    }
  },
  data() {
    return {
      // 选中数组
      ids: [],
      // 当前编辑ID
      updateId: '',
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: false,
      // 当前表单配置信息
      formConfig: {},
      // 数据表格信息
      table: {
        //表格的ref
        ref: 'tables',
        //表单设计Key
        formBuildKey: '',
        // 遮罩层
        loading: false,
        //表格高度
        tabHeight: 0,
        //表格字段信息
        tableColumnInfo: [],
        //表格操作按钮信息
        tableBtns: [],
        /** 列表按钮区宽度 */
        tableBtnsBoxWidth: 200,
        // 总条数
        total: 0,
        //翻译懒加载字段
        beLazyField:[],
      },
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 浏览类型 UPDATE：修改、DETAIL：查看详情
      VisitType: '',
      // 是否显示流程发起对话框
      procOpen: false,
      // 流程组件参数
      ProcParams: {},
      // 字段信息
      fieldInfo: [],
      // 查询参数
      form: {
        pageNum: 1,
        pageSize: 10,
        timeParams: {},
        '$SuperQuery$': null // 高级查询
      },
      //表格数据
      tableData: [],
      //判断当前模块是否启用流程
      isEnabledProc: '0',
      //加载类型
      initType: '',
      //业务模块访问配置
      visitConfig: null,
      //业务模块生成ID
      tabGenId: '',
      //业务模块配置信息
      modeConfig: {},
      //API前缀
      prefixUrl: '',
      //表单设计Key
      formBuildKey: '',
      //表单设计是否配置
      formBuildConfigOrNot: true,
      //当前为选择组件的选项值
      formDataOptions: {},
      //组件描述
      componentDesc: '',
      //数据导入配置
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 标记是否正在上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: {Authorization: "Bearer " + getToken()},
        // 上传的地址
        url: '',
      },
      //优树搭业务流程进度配置信息
      mksFlowConfig: {
        title: "流程进度",
        taskUuid: "",
        isOpen: false
      }
    }
  },
  created() {

  },
  methods: {
    /** 初始化业务模块参数 **/
    initModeParams() {
      //业务模块生成ID
      this.tabGenId = this.$route.params.tabGenId;
      this.visitConfig = {
        "tableId": this.tabGenId,
        "genType": this.isNotEmpty(this.tabGenId) ? "2" : "1",
        "baseUrlPrefix": this.prefixUrl
      }
      let matcheds = this.$route.matched.filter(item => item.meta && item.meta.title)
      if (matcheds) {
        let nowMeta = matcheds[matcheds.length - 1]
        this.componentDesc = nowMeta.meta.title
      }
      /** 初始化字段信息 **/
      this.initField()
    },
    /** 初始化字段信息 **/
    initField() {
      if (this.isEmpty(this.tabGenId) && this.isEmpty(this.prefixUrl)) {
        console.log("模块请求路径或模块ID为空，中止加载...");
        return;
      }
      init(this.tabGenId, this.prefixUrl).then(res => {
        if (res.code == 200) {
          let config = res.data;
          if (config == null || config == undefined) {
            this.msgError('获取配置信息失败')
            return;
          }
          this.modeConfig = config;
          if (this.isNotEmpty(this.tabGenId)) {
            //API前缀
            this.prefixUrl = config.prefixUrl
            //表单设计Key
            this.formBuildKey = config.formBuildKey
            this.formBuildConfigOrNot = config.formBuildConfigOrNot
            //组件描述
            if (this.isEmpty(this.componentDesc)) {
              this.componentDesc = config.componentDesc
            }
          }
          //当前表单配置信息
          this.formConfig = config.formConfig || formConf
          /** 加载表格配置信息 **/
          this.initTableInf(config)
          /** 翻译懒加载字段 */
          this.initBeLazyField()
          /** 查询数据 **/
          this.initLoadData(config.fieldInfos);
        } else {
          this.msgError(res.msg)
        }
      })
    },
    /** 获取懒加载的字段 */
    initBeLazyField() {
      let beLazyField = [];
      const tableColumnInfo = this.table.tableColumnInfo;
      let c_index = 0;
      tableColumnInfo.forEach(item => {
        if (item.beLazyDictConfig && item.beLazyDictConfig.beLazy === '1') {
          beLazyField.push({
            field: item.javaField,
            dictType: item.dictType,
            dictItems: item.beLazyDictConfig.dictItems,
            c_index: c_index,
          })
        }
        c_index++;
      })
      this.table.beLazyField = beLazyField;
    },
    /** 加载表格配置信息 **/
    initTableInf(config) {
      //表单设计Key
      this.table.formBuildKey = this.formBuildKey
      /** 记录列表字段信息 **/
      if (config.fieldInfos) {
        this.table.tableColumnInfo = JSON.parse(JSON.stringify(config.fieldInfos));
      }
      /** 列表区按钮信息 */
      if (config.crudBtnsList) {
        let tableBtns = config.crudBtnsList.filter((btn, index, self) => {
          return btn.isEnabled && (btn.areaType == 'A' || btn.areaType == 'L') && hasPermissions([`${btn['hasPermi']}`])
        })
        this.table.tableBtns = tableBtns
        this.table.tableBtnsBoxWidth = this.listOperBtnBoxWidth
      }
      /** 数据表格风格配置 */
      let tableModuleType = 'Default'
      if (config.crudTableConfig) {
        Object.assign(this.table, config.crudTableConfig)
        //组件ID
        this.table['ref'] = this.generateUuid()

        tableModuleType = this.table['moduleType']
      }
      /**
       * 加载数据表格
       */
      this.loadTableComponent(tableModuleType);
    },
    /** 加载字段 **/
    initLoadData(fieldInfo) {
      this.fieldInfo = fieldInfo
      fieldInfo.forEach(item => {
        //查询参数
        this.form[item.columnName] = null
      })
      /** 获取列表数据 **/
      this.getList()
    },
    /** 获取表格分页信息，并获取数据 */
    handerPagination(pagination) {
      if (pagination) {
        this.form['pageNum'] = pagination['pageNum']
        this.form['pageSize'] = pagination['pageSize']
      }
      /** 查询列表数据 */
      this.getList()
    },
    /** 获取查询参数信息 **/
    getReqParams() {
      // 获取高级查询信息
      let superQueryInfo = this.form['$SuperQuery$']
      if (this.isNotEmpty(superQueryInfo)) {
        //高级查询
        return {
          '$SuperQuery$': superQueryInfo,
          'pageNum': this.form['pageNum'],
          'pageSize': this.form['pageSize']
        }
      } else {
        //根据查询区域信息查询
        return this.form
      }
    },
    /** 查询列表数据 */
    getList() {
      this.table.loading = true
      //清空当前数据
      this.tableData = []
      //请求数据
      list(this.tabGenId, this.prefixUrl, this.getReqParams()).then(response => {
        /**
         * 获取懒加载字段的翻译信息
         */
        let beLazyField = this.table.beLazyField;
        let _tableData = response.rows;
        if (beLazyField && beLazyField.length > 0) {
          let findValue;
          let fieldCount = 0;
          beLazyField.forEach(item => {
            findValue = [];
            fieldCount++;
            this.getBeLazyFindValue(item,  _tableData, findValue)
            /**
             * 查询字典信息
             */
            this.request({
              url: '/common/basemode/dictLazyLoad/'+item['dictType'],
              data: {
                fieldValue: findValue.join(','),
                field: 'fieldValue'
              },
              method: 'post'
            }).then((res) => {
              let dictItems = res.data;
              let _dictItems = this.table.tableColumnInfo[item.c_index].dictItems;
              if(_dictItems){
                _dictItems.push(...dictItems)
                this.table.tableColumnInfo[item.c_index].dictItems = _dictItems;
                this.formDataOptions[item.field] =  _dictItems;
              }
              if (dictItems.length > 0) {
                let __dictItems = item.dictItems;
                __dictItems.push(...findValue)
                item.dictItems = __dictItems;
              }
            }).finally(() => {
              if(fieldCount == beLazyField.length){
                this.tableData = response.rows?response.rows:[]
                let total = response.total
                if (!(total instanceof Number)) {
                  total = Number(total)
                }
                this.table.total = total
                this.table.loading = false
                // 重置数据表格的高度
                this.resetTableHeight()
              }
            })
          })
          this.table.beLazyField = beLazyField;
        }else{
          this.tableData = response.rows?response.rows:[]
          let total = response.total
          if (!(total instanceof Number)) {
            total = Number(total)
          }
          this.table.total = total
          this.table.loading = false
          // 重置数据表格的高度
          this.resetTableHeight()
        }
      })
    },
    /** 获取懒加载字段的value */
    getBeLazyFindValue(obj,_tableData,findValue){
      //获取未加载的字典信息
      let _value = '';
      _tableData.forEach(row => {
        _value = row[obj.field];
        if(!!_value && obj.dictItems.indexOf(_value)==-1 && findValue.indexOf(_value)==-1){
          findValue.push(row[obj.field])
        }
        //树形表格
        if(row['_childrenData'] && row['_childrenData'].length>0){
          this.getBeLazyFindValue(obj,row['_childrenData'],findValue)
        }
      })
    },
    /** 更新快速设置后的信息 **/
    changeModeConfig(modeConfig) {
      this.modeConfig = modeConfig;
    },
    /** 表单同步数据 **/
    ItemValChange(data, configInfo) {
      // 修改表单信息
      this.form[data.key] = data.val
      // 当在查询区域录入信息后，则清空高级查询信息
      this.form['$SuperQuery$'] = null
      // 标记事件运行时作用域     列表查询区域为 true、表单操作区域为false
      this.isQueryScope = true
      /** 执行事件对应逻辑 **/
      if (configInfo && this.isNotEmpty(configInfo['onChangeEventCode'])) {
        this.evalEventCode(configInfo['onChangeEventCode'], null);
      }
    },
    /** 设置表单字段值 **/
    setFieldValue(fieldName, fieldValue) {
      if (fieldName) {
        this.$set(this.form, fieldName, fieldValue)
        this.changeFieldConfigValue(fieldName, 'fieldData', fieldValue)
      }
    },
    setSelectionOptions(fieldName, dictObj, otherParam) {
      /** 当字典参数为空或即不是数组也不是字符串时，默认为无效选项直接赋值空数组 **/
      if (dictObj == null || dictObj == undefined || (!Array.isArray(dictObj) && typeof dictObj !== 'string')) {
        dictObj = []
      }
      /** 字典参数为数组时，直接修改到组件上 **/
      if (Array.isArray(dictObj)) {
        // 字典选项
        this.changeFieldConfigValue(fieldName, 'dictItems', dictObj)
        return;
      }
      /** 字典参数为字符串时，请求服务器获取字典信息再修改到组件上 **/
      if (typeof dictObj === 'string') {
        if (otherParam) {
          // 请求优树搭获取字典选项信息
          this.getYsdApiData(dictObj, otherParam).then(response => {
            let parseOptions = []
            if (response.data && Array.isArray(response.data)) {
              parseOptions = response.data
            }
            this.changeFieldConfigValue(fieldName, 'dictItems', parseOptions)
            return;
          });
        } else {
          // 获取平台字典编码
          this.getDicts(dictObj).then(response => {
            let parseOptions = []
            if (Array.isArray(response.data)) {
              parseOptions = response.data
            }
            this.changeFieldConfigValue(fieldName, 'dictItems', parseOptions)
            return;
          })
        }
      }
    },
    /**
     * 修改字段配置信息中对应值
     */
    changeFieldConfigValue(fieldName, key, val) {
      if (!Array.isArray(this.fieldInfo)) {
        return;
      }
      if (this.isEmpty(fieldName)) {
        this.msgError("处理字段不能为空");
        return;
      }
      for (let col of this.fieldInfo) {
        if (col['columnName'] == fieldName) {
          this.$set(col, key, val)
          break;
        }
      }
    },
    /** 取消按钮 **/
    cancel(param) {
      this.updateId = ''
      this.open = false
      this.procOpen = false;
      if (param != undefined && param.isRef == true) {
        this.getList()
        this.$emit('change', null)
      }
      // 清空当前操作行的对象
      this.rowData = null
    },
    /** 搜索按钮操作 */
    handleQuery(superQueryInfo) {
      this.form.pageNum = 1
      // 添加高级查询信息
      this.form['$SuperQuery$'] = superQueryInfo || ''
      // 查询数据
      this.getList()
    },
    /** 重置查询表单信息 **/
    resetQuery() {
      this.form['timeParams'] = {}
      this.fieldInfo.forEach((item, index) => {
        this.$set(this.fieldInfo[index], 'fieldData', null)
        this.form[item.columnName] = null
      })
      this.handleQuery()
    },
    /** 多选框选中数据 */
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.defPk)
      //当前选择的行数据
      this.selectRowData = selection
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 排序触发事件 */
    handleSortChange(column) {
      this.form['orderByColumn'] = column.prop
      this.form['isAsc'] = column.order
      this.getList();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.updateId = ''
      this.open = true
      this.title = '添加' + this.componentDesc
    },
    /** 详情按钮操作 */
    handleDetail() {
      this.title = '查看' + this.componentDesc + "详情"
      this.openUpdateInfo('DETAIL');
    },
    /** 修改按钮操作 */
    handleUpdate() {
      this.title = '修改' + this.componentDesc
      this.openUpdateInfo('UPDATE');
    },
    openUpdateInfo(type) {
      if ((this.rowData == undefined || this.rowData == null) && this.ids.length != 1) {
        this.msgError('请选择需要操作1条的数据')
        return;
      }
      this.updateId = this.rowData && this.rowData.defPk || this.ids;
      this.VisitType=type
      this.open = true
    },
    /** 为表格赋值数据 **/
    handleAssignTableData(listData){
      if(listData == undefined || listData == null){
        listData = []
      }
      //给数据列表赋值
      this.tableData = listData
      //修改数据条数
      this.table.total = listData.length
      this.table.loading = false
      // 重置数据表格的高度
      this.resetTableHeight()
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      var that = this;
      if ((row == undefined || row == null) && (this.rowData == undefined || this.rowData == null) && this.ids.length <= 0) {
        this.msgError('请选择需要操作的数据')
        return;
      }
      const ids = row && row.defPk || this.rowData && this.rowData.defPk || this.ids;

      this.$confirm('是否确认删除勾选数据项?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function () {
        return del(that.tabGenId, that.prefixUrl, ids);
      }).then(() => {
        this.getList()
        this.msgSuccess('删除成功')
        // 清空当前操作行的对象
        this.rowData = null
        this.$emit('change', null)
      })
    },
    /** 下载模板操作 */
    importTemplate() {
      let url = this.prefixUrl + '/importTemplate'
      if (this.isNotEmpty(this.tabGenId)) {
        url = '/common/basemode/importTemplate/' + this.tabGenId
      }
      this.download(url, {
        ...this.form
      }, `${this.componentDesc + '_模块'}.xlsx`)
    },
    /** 导入按钮操作 */
    handleImport() {
      if (this.isNotEmpty(this.tabGenId)) {
        this.upload.url = process.env.VUE_APP_BASE_API + "/common/basemode/importData/" + this.tabGenId
      }
      this.upload.title = this.componentDesc;
      this.upload.open = true;
    },
    /** 导出按钮操作 */
    handleExport() {
      var that = this;
      const form = JSON.parse(JSON.stringify(this.getReqParams()));
      form['pageSize'] = this.$store.getters.sysMaxExportCount;
      let url = this.prefixUrl + '/export'
      if (this.isNotEmpty(this.tabGenId)) {
        url = '/common/basemode/export/' + this.tabGenId
      }
      this.$confirm('是否确认导出当前查询结果所有数据，最多可导出' + form['pageSize'] + '条数据?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function () {
        that.download(url, {
          ...form
        }, `${that.componentDesc + '_' + new Date().getTime()}.xlsx`)
      })
    },
    // 自定义上传
    customRequest(params) {
      console.log("customRequest:",params);
      const formData = new FormData();
      formData.append('file', params.file);

      // 创建axios实例并设置超时时间（单位：毫秒）
      const instance = axios.create({
        timeout: (this.upload.uploadTimeout || 20)*1000, // 设置超时时间
        headers: {
          Authorization: "Bearer " + getToken(),
        }
      });

      instance.post(this.upload.url, formData)
        .then(response => {
          console.log("result:",response);
          params.onSuccess(response.data);
        })
        .catch(error => {
          if (axios.isCancel(error)) {
            console.log('Request canceled', error.message);
          } else if (error.code === 'ECONNABORTED') {
            // 超时处理
            params.onError(new Error('上传超时，请重试'));
          } else {
            params.onError(error);
          }
        });
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(response.msg, "处理结果", {dangerouslyUseHTMLString: true});
      this.getList();
      // 清空当前操作行的对象
      this.rowData = null
      this.$emit('change', null)
    },
    handleFileError(err, file, fileList) {
      console.log(err,file);
    },
    // 提交上传文件
    submitFileForm() {
      //执行上传
      this.$refs.upload.submit();
    },
    // 取消上传文件
    cancelFileForm() {
      this.upload.open = false
      this.$refs.upload.clearFiles();
    },
    // 重置数据表格的高度
    resetTableHeight() {
      this.$nextTick(() => {
        if (this.table['loadMode'] == 'design') {
          return;
        }
        this.table.tabHeight = this.table._tabHeight + 16
        if (this.showSearch) {
          /**
           * 显示搜索区域时
           */
          this.table.tabHeight = this.table._tabHeight - this.$refs.queryForm.$el.offsetHeight + 10
        }
        // 重新渲染表格
        try {
          this.$refs[this.table.ref].doLayout();
        } catch (e) {
        }
      })
    },

  },
  beforeMount() {
    /** 适配数据表格高度 **/
    this.table._tabHeight = this.appMain.height - 135
  },
  // 页面缓存重新进入页面时，在路由组件被激活时触发
  activated() {
    this.$nextTick(() => {
      this.$refs[this.table.ref].doLayout(); // 对表格重新布局（解决切换页面后列错乱）
    })
  },

  watch: {
    /** 监听查询输入是否显示，适配数据表格高度 **/
    showSearch: {
      immediate: true,
      handler(nowdata) {
        this.resetTableHeight();
      }
    },
  }
}
